/**
 * 店铺申请审核系统
 */

// 全局变量
let applications = [];
let currentPage = 1;
let rowsPerPage = 10;
let totalPages = 0;
let totalApplications = 0;

// DOM元素
const tableBody = document.getElementById('tableBody');
const pageNumbers = document.getElementById('pageNumbers');
const prevPage = document.getElementById('prevPage');
const nextPage = document.getElementById('nextPage');
const pageSizeSelect = document.getElementById('pageSize');
const shopName = document.getElementById('shopName');
const statusFilter = document.getElementById('statusFilter');
const searchBtn = document.getElementById('searchBtn');
const loader = document.getElementById('compact-loader');

// 统计元素
const totalApplicationsElement = document.getElementById('totalApplications');
const pendingApplicationsElement = document.getElementById('pendingApplications');
const approvedApplicationsElement = document.getElementById('approvedApplications');
const rejectedApplicationsElement = document.getElementById('rejectedApplications');

// 初始化页面
function init() {
    renderTable();
    addEventListeners();
}

// 渲染表格
function renderTable() {
    showLoader();

    const searchData = {
        shopName: shopName.value || '',
        status: statusFilter.value || '',
        page: currentPage,
        pageSize: rowsPerPage
    };

    console.log('请求参数:', searchData);

    $.ajax({
        url: '/shopAduit/list',
        type: 'POST',
        data: searchData,
        success: function (data) {
            if (data.code == 200) {
                console.log('响应数据:', data);

                // 直接使用后端返回的数据，不需要前端再次分页和过滤
                applications = data.data.rows || [];
                totalApplications = data.data.total;
                totalPages = Math.ceil(totalApplications / rowsPerPage);

                console.log('分页信息:', {
                    currentPage,
                    totalPages,
                    totalApplications,
                    rowsPerPage,
                    applicationsCount: applications.length
                });

                // 渲染表格内容
                renderTableBody();

                // 渲染分页控件
                renderPagination();

                hideLoader();
            } else {
                console.error('API返回错误:', data.message);
                showError('获取申请数据失败: ' + data.message);
                hideLoader();
            }
        },
        error: function(xhr, status, error) {
            console.error('请求失败:', error);
            showError('网络请求失败，请稍后重试');
            hideLoader();
        }
    });
}

// 渲染表格内容
function renderTableBody() {
    tableBody.innerHTML = '';

    console.log('渲染表格数据:', applications);

    if (applications.length === 0) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="7" class="text-center py-4 text-muted">
                    <i class="bi bi-inbox"></i> 暂无申请数据
                </td>
            </tr>
        `;
        return;
    }

    applications.forEach(application => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${application.id}</td>
            <td>
                ${application.avatarUrl ?
            `<img src="${application.avatarUrl}" class="shop-avatar" alt="${application.shopName}的头像">` :
            `<div class="shop-avatar-placeholder"><i class="bi bi-shop"></i></div>`
        }
            </td>
            <td>
                <div class="shop-info">
                    <div class="shop-name">${escapeHtml(application.shopName || '')}</div>
                    <div class="shop-desc">${escapeHtml(application.shopDesc || '')}</div>
                </div>
            </td>
            <td>${escapeHtml(application.username || '')}</td>
            <td>${application.createdTime}</td>
            <td>
                <span class="status-badge ${getStatusClass(application.status)}">
                    ${getStatusText(application.status)}
                </span>
            </td>
            <td>
                <button class="btn-view" data-id="${application.id}">
                    <i class="bi bi-eye"></i> 查看
                </button>
                ${application.status === 1 ? `
                <button class="btn-approve" data-id="${application.id}">
                    <i class="bi bi-check-lg"></i> 通过
                </button>
                <button class="btn-reject" data-id="${application.id}">
                    <i class="bi bi-x-lg"></i> 拒绝
                </button>
                ` : ''}
            </td>
        `;
        tableBody.appendChild(row);
    });
}

// 获取状态类名
function getStatusClass(status) {
    switch(parseInt(status)) {
        case 1: return 'status-pending';
        case 0: return 'status-approved';
        case 2: return 'status-rejected';
        default: return '';
    }
}

// 获取状态文本
function getStatusText(status) {
    switch(parseInt(status)) {
        case 1: return '待审核';
        case 0: return '已通过';
        case 2: return '已拒绝';
        default: return '未知';
    }
}

// 渲染分页
function renderPagination() {
    console.log('渲染分页 - 当前页:', currentPage, '总页数:', totalPages, '总申请数:', totalApplications);

    pageNumbers.innerHTML = '';

    // 上一页按钮状态
    prevPage.disabled = currentPage === 1;

    // 下一页按钮状态
    nextPage.disabled = currentPage === totalPages || totalPages === 0;

    // 如果没有数据或只有一页，显示单个页码
    if (totalPages <= 1) {
        if (totalPages === 1) {
            const pageBtn = document.createElement('button');
            pageBtn.className = 'page-btn active';
            pageBtn.textContent = '1';
            pageBtn.addEventListener('click', () => goToPage(1));
            pageNumbers.appendChild(pageBtn);
        }
        return;
    }

    // 多页情况下的页码显示逻辑
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    // 调整起始页，确保显示足够的页码
    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    // 显示第一页和省略号（如果需要）
    if (startPage > 1) {
        const firstPage = document.createElement('button');
        firstPage.className = 'page-btn';
        firstPage.textContent = '1';
        firstPage.addEventListener('click', () => goToPage(1));
        pageNumbers.appendChild(firstPage);

        if (startPage > 2) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.style.padding = '0 10px';
            ellipsis.style.color = '#6c757d';
            pageNumbers.appendChild(ellipsis);
        }
    }

    // 显示中间页码
    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.className = `page-btn ${i === currentPage ? 'active' : ''}`;
        pageBtn.textContent = i;
        pageBtn.addEventListener('click', () => goToPage(i));
        pageNumbers.appendChild(pageBtn);
    }

    // 显示最后一页和省略号（如果需要）
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.style.padding = '0 10px';
            ellipsis.style.color = '#6c757d';
            pageNumbers.appendChild(ellipsis);
        }

        const lastPage = document.createElement('button');
        lastPage.className = 'page-btn';
        lastPage.textContent = totalPages;
        lastPage.addEventListener('click', () => goToPage(totalPages));
        pageNumbers.appendChild(lastPage);
    }
}

// 跳转到指定页码
function goToPage(page) {
    console.log('跳转页面: 从', currentPage, '到', page);

    if (page < 1 || page > totalPages || page === currentPage) {
        return;
    }

    currentPage = page;
    renderTable(); // 重新请求数据并渲染
}

// 显示加载动画
function showLoader() {
    if (loader) {
        loader.style.display = 'flex';
    }
}

// 隐藏加载动画
function hideLoader() {
    if (loader) {
        loader.style.display = 'none';
    }
}

// 显示成功消息
function showSuccess(message) {
    const alert = document.getElementById('success-alert');
    const messageSpan = document.getElementById('success-message');
    if (alert && messageSpan) {
        messageSpan.textContent = message;
        alert.style.display = 'flex';

        setTimeout(() => {
            alert.style.display = 'none';
        }, 2000);
    }
}

// 显示错误消息
function showError(message) {
    const alert = document.getElementById('error-alert');
    const messageSpan = document.getElementById('error-message');
    if (alert && messageSpan) {
        messageSpan.textContent = message;
        alert.style.display = 'flex';

        setTimeout(() => {
            alert.style.display = 'none';
        }, 2000);
    }
}

// HTML转义函数
function escapeHtml(unsafe) {
    if (!unsafe) return '';
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// 处理申请操作
function handleApplicationAction(id, action) {
    const application = applications.find(app => app.id === id);
    console.log(application)
    if (!application) return;

    const actionText = action === 'approve' ? '通过' : '拒绝';
    const apiUrl = action === 'approve' ? 'shopAduit/approve' : 'shopAduit/reject';

    // 创建自定义弹窗
    const modal = document.createElement('div');
    modal.className = 'custom-modal';
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
    `;

    modal.innerHTML = `
        <div style="background: white; padding: 20px; border-radius: 8px; width: 400px; max-width: 90%;">
            <h3>${actionText}申请</h3>
            <p>确定要${actionText}店铺 "<strong>${application.shopName}</strong>" 的店铺申请吗？</p>
            <div style="margin: 15px 0;">
                <label style="display: block; margin-bottom: 5px; font-weight: bold;">${actionText}理由：</label>
                <textarea 
                    id="reasonInput" 
                    placeholder="请输入${actionText}理由..." 
                    style="width: 100%; height: 80px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; resize: vertical;"
                ></textarea>
            </div>
            <div style="text-align: right; margin-top: 20px;">
                <button id="cancelBtn" style="padding: 8px 16px; margin-right: 10px; border: 1px solid #ddd; background: #f5f5f5; border-radius: 4px; cursor: pointer;">取消</button>
                <button id="confirmBtn" style="padding: 8px 16px; border: none; background: ${action === 'approve' ? '#1890ff' : '#ff4d4f'}; color: white; border-radius: 4px; cursor: pointer;">确定${actionText}</button>
            </div>
        </div>
    `;

    document.body.appendChild(modal);

    // 取消按钮事件
    document.getElementById('cancelBtn').onclick = function() {
        document.body.removeChild(modal);
    };

    // 确定按钮事件
    document.getElementById('confirmBtn').onclick = function() {
        const reasonInput = document.getElementById('reasonInput');
        const reason = reasonInput.value.trim();

        if (!reason) {
            alert(`${actionText}理由不能为空！`);
            reasonInput.focus();
            return;
        }

        // 移除弹窗
        document.body.removeChild(modal);

        // 执行AJAX请求
        showLoader();
        console.log('执行AJAX请求:', reason)
        $.ajax({
            url: apiUrl,
            type: 'POST',
            data: {
                id: id,
                name: $.cookie("adminName"),  // 保持为 username
                aduitDesc: reason
            },
            success: function (data) {
                if (data.code == 200) {
                    showSuccess(`已${actionText}用户 ${application.username} 的店主申请`);
                    renderTable(); // 重新加载数据
                } else {
                    showError(`操作失败: ${data.message}`);
                    hideLoader();
                }
            },
            error: function(xhr, status, error) {
                console.error('操作失败:', error);
                showError('操作失败，请稍后重试');
                hideLoader();
            }
        });
    };

    // 按ESC键关闭弹窗
    modal.onkeydown = function(e) {
        if (e.key === 'Escape') {
            document.body.removeChild(modal);
        }
    };

    // 点击背景关闭弹窗
    modal.onclick = function(e) {
        if (e.target === modal) {
            document.body.removeChild(modal);
        }
    };

    // 自动聚焦到输入框
    setTimeout(() => {
        document.getElementById('reasonInput').focus();
    }, 100);
}
// 添加事件监听器
function addEventListeners() {
    // 分页按钮
    prevPage.addEventListener('click', () => {
        if (currentPage > 1) {
            goToPage(currentPage - 1);
        }
    });

    nextPage.addEventListener('click', () => {
        if (currentPage < totalPages) {
            goToPage(currentPage + 1);
        }
    });

    // 每页显示条数选择器
    pageSizeSelect.addEventListener('change', (e) => {
        rowsPerPage = parseInt(e.target.value);
        currentPage = 1; // 重置到第一页
        renderTable();
    });

    // 搜索按钮
    searchBtn.addEventListener('click', () => {
        currentPage = 1; // 重置到第一页
        renderTable();
    });

    // 搜索框回车事件
    shopName.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            currentPage = 1;
            renderTable();
        }
    });

    // 状态筛选变化
    statusFilter.addEventListener('change', () => {
        currentPage = 1;
        renderTable();
    });

    // 表格按钮事件委托
    tableBody.addEventListener('click', (e) => {
        const target = e.target.closest('button');
        if (!target) return;

        const id = parseInt(target.getAttribute('data-id'));
        const application = applications.find(app => app.id === id);
        if (!application) return;

        if (target.classList.contains('btn-view')) {
            // 查看按钮
            // alert(`查看申请详情\n店铺名称: ${application.shopName}\n店铺描述: ${application.shopDesc}\n店主: ${application.username}\n申请时间: ${application.createdTime}\n状态: ${getStatusText(application.status)}`);
            var shopdata;
            $.ajax({
                url: '/shopAduit/getShopAduitById',
                type: 'POST',
                data: { id: id },
                async: false,
                success: function (data) {
                    shopdata = data.data
                }
            })
            showShopAuditModal(shopdata)
        } else if (target.classList.contains('btn-approve')) {
            // 通过按钮
            handleApplicationAction(id, 'approve');
        } else if (target.classList.contains('btn-reject')) {
            // 拒绝按钮
            handleApplicationAction(id, 'reject');
        }
    });

    // 提示框关闭按钮
    document.querySelectorAll('.alert-close').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const alert = e.target.closest('.alert');
            if (alert) {
                alert.style.display = 'none';
            }
        });
    });
}

// 初始化应用
document.addEventListener('DOMContentLoaded', init);
let currentAuditShop = null;
let currentAuditSlide = 0;
let auditTotalSlides = 0;

// 显示店铺审核详情模态框
function showShopAuditModal(shopData) {
    currentAuditShop = shopData;
    console.log(shopData)
    // 填充基本信息
    $('#auditApplicationId').text(shopData.id || '-');
    $('#auditShopName').text(shopData.shopName || '-');
    // $('#auditOwnerId').text(shopData.ownerId || '-');
    $('#auditOwnerName').text(shopData.username || '-');
    $('#auditPhone').text(shopData.phone || '-');
    $('#auditApplyTime').text(formatDate(shopData.createdTime) || '-');

    // 设置店铺头像
    if (shopData.avatarUrl) {
        $('#auditShopAvatar').attr('src', shopData.avatarUrl);
    }

    // 设置状态
    updateAuditStatus(shopData.status);

    // 填充店铺详情
    $('#auditDescription').text(shopData.shopDesc || '暂无简介');
    $('#auditAddress').text(shopData.address || '未填写地址');
    $('#auditBusinessHours').text((shopData.openTime+" - "+shopData.closeTime) || '未设置');
    $('#auditAvgPrice').text(shopData.avgPrice ? `¥${shopData.avgPrice}` : '未设置');
    $('#auditShopPhone').text(shopData.shopPhone || '-');

    // 设置轮播图
    setupAuditCarousel(shopData.bannerUrls || []);

    // 显示审核信息（如果已审核）
    if (shopData.status !== 1) { // 不是待审核状态
        $('#auditInfoSection').show();
        $('#auditReviewer').text(shopData.aduitPerson || '-');
        $('#auditReviewTime').text(formatDate(shopData.aduitTime) || '-');
        $('#auditReviewNote').text(shopData.aduitDesc || '无备注');

        // 隐藏操作按钮
        $('#auditActionButtons').hide();
    } else {
        $('#auditInfoSection').hide();
        $('#auditActionButtons').show();
    }

    // 显示模态框
    $('#shopAuditModal').show();
    $('body').css('overflow', 'hidden');
}

// 更新审核状态显示
function updateAuditStatus(status) {
    const statusBadge = $('#auditStatusBadge');
    statusBadge.removeClass('status-pending status-approved status-rejected');

    switch(status) {
        case 1: // 待审核
            statusBadge.addClass('status-pending').html('<i class="bi bi-clock"></i> 待审核');
            break;
        case 0: // 已通过
            statusBadge.addClass('status-approved').html('<i class="bi bi-check-circle"></i> 已通过');
            break;
        case 2: // 已拒绝
            statusBadge.addClass('status-rejected').html('<i class="bi bi-x-circle"></i> 已拒绝');
            break;
        default:
            statusBadge.text('-');
    }
}

// 设置轮播图
function setupAuditCarousel(images) {
    const carouselSlides = $('#auditCarouselSlides');
    const indicators = $('#auditCarouselIndicators');
    const noImagesMessage = $('#auditNoImagesMessage');
    const carouselContainer = $('#auditCarouselContainer');

    carouselSlides.empty();
    indicators.empty();

    if (!images || images.length === 0) {
        carouselContainer.hide();
        noImagesMessage.show();
        $('#auditCurrentSlide').text('0');
        $('#auditTotalSlides').text('0');
        return;
    }

    carouselContainer.show();
    noImagesMessage.hide();
    images = JSON.parse(images)
    // 创建轮播图幻灯片
    images.forEach((image, index) => {
        carouselSlides.append(`
            <div class="carousel-slide">
                <img src="${image}" alt="店铺图片 ${index + 1}" 
                     onerror="this.src=''">
            </div>
        `);

        indicators.append(`
            <div class="carousel-indicator ${index === 0 ? 'active' : ''}" 
                 onclick="goToAuditSlide(${index})"></div>
        `);
    });

    auditTotalSlides = images.length;
    currentAuditSlide = 0;
    updateAuditCarouselCounter();
}

// 轮播图控制函数
function prevAuditSlide() {
    if (auditTotalSlides === 0) return;
    currentAuditSlide = (currentAuditSlide - 1 + auditTotalSlides) % auditTotalSlides;
    updateAuditCarousel();
}

function nextAuditSlide() {
    if (auditTotalSlides === 0) return;
    currentAuditSlide = (currentAuditSlide + 1) % auditTotalSlides;
    updateAuditCarousel();
}

function goToAuditSlide(index) {
    currentAuditSlide = index;
    updateAuditCarousel();
}

function updateAuditCarousel() {
    const carouselSlides = $('#auditCarouselSlides');
    const indicators = $('.carousel-indicator');

    carouselSlides.css('transform', `translateX(-${currentAuditSlide * 100}%)`);

    indicators.removeClass('active');
    indicators.eq(currentAuditSlide).addClass('active');

    updateAuditCarouselCounter();
}

function updateAuditCarouselCounter() {
    $('#auditCurrentSlide').text(currentAuditSlide + 1);
    $('#auditTotalSlides').text(auditTotalSlides);
}

// 关闭模态框
function closeShopAuditModal() {
    $('#shopAuditModal').hide();
    $('body').css('overflow', 'auto');
    currentAuditShop = null;
}

// 审核操作
function approveShopApplication() {
    if (!currentAuditShop) return;

    if (confirm('确定要通过这个店铺申请吗？')) {
        // 调用审核通过API
        submitAuditAction(currentAuditShop.id, 2, '申请通过');
    }
}

function rejectShopApplication() {
    if (!currentAuditShop) return;

    const reason = prompt('请输入拒绝原因：');
    if (reason !== null && reason.trim() !== '') {
        // 调用审核拒绝API
        submitAuditAction(currentAuditShop.id, 3, reason);
    }
}

function submitAuditAction(applicationId, status, note) {
    showLoading();

    $.ajax({
        url: '/api/shop-applications/audit',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            applicationId: applicationId,
            status: status,
            reviewNote: note
        }),
        headers: {
            'X-CSRF-TOKEN': getCsrfToken()
        },
        success: function(response) {
            hideLoading();
            if (response.success) {
                showSuccessAlert(status === 2 ? '申请已通过' : '申请已拒绝');
                closeShopAuditModal();
                // 刷新表格数据
                loadShopApplications();
            } else {
                showErrorAlert(response.message || '操作失败');
            }
        },
        error: function(xhr, status, error) {
            hideLoading();
            showErrorAlert('操作失败: ' + (xhr.responseJSON?.message || error));
        }
    });
}

// 工具函数
function formatDate(dateString) {
    if (!dateString) return '-';
    try {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    } catch (e) {
        return '-';
    }
}

function getCsrfToken() {
    return $('meta[name="_csrf"]').attr('content') ||
        $('input[name="_csrf"]').val() ||
        $.cookie('XSRF-TOKEN');
}

// 点击模态框外部关闭
$(document).on('click', function(e) {
    if ($(e.target).is('#shopAuditModal')) {
        closeShopAuditModal();
    }
});

// ESC键关闭
$(document).on('keydown', function(e) {
    if (e.keyCode === 27) {
        closeShopAuditModal();
    }
});